﻿<template>
  <div>
    <a-card :bordered="false" :bodyStyle="tstyle">
      <div class="table-page-search-wrapper" v-if="hasPerm('FoamingRuKuOrder:page')">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="批次">
                <a-input v-model="queryParam.batch" allow-clear placeholder="请输入批次"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="密度">
                <a-input v-model="queryParam.MaterialDensity" allow-clear placeholder="请输入密度"/>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="单据编号">
                  <a-input v-model="queryParam.OrderNo" allow-clear placeholder="请输入单据编号"/>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select :allowClear="true" style="width: 100%" v-model="queryParam.orderStatus" placeholder="请选择状态">
                    <a-select-option v-for="(item,index) in orderStatusData" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>      
              <a-col :md="8" :sm="24">
              <a-form-item label="入库单类型">
                <a-select :allowClear="true" style="width: 100%" v-model="queryParam.OrderSubclass" placeholder="请选择入库单类型">
                  <a-select-option v-for="(item,index) in orderSubclassData" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
                <a-form-item label="下料产线">
                  <a-select :allowClear="true" style="width: 100%" v-model="queryParam.BlankingProductionLine" placeholder="请选择下料产线">
                    <a-select-option v-for="(item,index) in blankingProductionLineList" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="入库口">
                  <a-select :allowClear="true" style="width: 100%" v-model="queryParam.PreferredPort" placeholder="请选择入库口">
                    <a-select-option v-for="(item,index) in preferredPortList" :key="index" :value="item.code">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="创建时间">
                  <a-range-picker v-model="queryParam.dateRange" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="8" :sm="24" >
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="$refs.table.refresh(true)" >查询</a-button>
                <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px"> {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false">
      <s-table
        ref="table"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowKey="(record) => record.id"
        :pageSize="5"
        :pageSizeOptions="['5','10','20','30']"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template class="table-operator" slot="operator" v-if="hasPerm('fp_rk_action')">
          <a-button type="primary" icon="plus" @click="$refs.form.init('add')">新增</a-button>
          <a-button type="danger" icon="step-forward" :disabled="!selectDistributes.length" @click="onMulDistribute">下发</a-button>
          <a-button type="danger" icon="delete" :disabled="!selectDels.length" @click="onMulDel">删除</a-button>
        </template>
        <span slot="orderStatusscopedSlots" slot-scope="text">
          <a-tag :color="text===2?'#0000ff':(text===3?'#008000':(text===4?'#ffd700':'gray'))">{{ 'order_status' | dictType(text) }}</a-tag>
        </span>
        <span slot="taskModelscopedSlots" slot-scope="text">
          <a-tag :color="text===1?'#90ee90':(text===2?'#1e90ff':(text===3?'#00ffff':'gray'))">{{ 'task_model' | dictType(text) }}</a-tag>
        </span>
        <template slot="blankingProductionLineSlots" slot-scope="text">
        {{ 'blanking_production_line' | dictType(text) }}
      </template>
        <template slot="linkSlot" slot-scope="text,record">
          <a @click="onViewDetail(record)">{{text}}</a>
        </template>
        <span slot="action" slot-scope="text, record">
          <a :class="[record.orderStatus===1||record.orderStatus===4?'':'disabled']" style="margin-right:10px;" @click="onEdit(record)">编辑</a>
          <a-dropdown>
            <a class="ant-dropdown-link" @click="e => e.preventDefault()">更多...</a>
            <a-menu slot="overlay">
              <a-menu-item><a :class="[record.orderStatus===2?'':'disabled']" style="margin-right:10px;" @click="onForceComplete(record)">完成</a></a-menu-item>
              <a-menu-item><a :class="[record.orderStatus===2||record.orderStatus===3?'':'disabled']" style="margin-right:10px;" @click="onOpenNumberChangeModal(record)">增补数量</a></a-menu-item>
              <a-menu-item><a :class="[record.orderStatus===1||record.orderStatus===4?'':'disabled']" style="margin-right:10px;" @click="onDistribute(record)">下发</a></a-menu-item>
              <!-- <a-menu-item><a :class="[record.orderStatus===1||record.orderStatus===2?'':'disabled']" @click="onWithdraw(record)" style="margin-right:10px;">撤回</a></a-menu-item> -->
              <a-menu-item><a :class="[record.orderStatus===1||record.orderStatus===4?'':'disabled']" @click="onDel(record)">删除</a></a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </s-table>
      
      <info-block :query-id="infoId" v-if="infoId" :order-no="infoOrderNo" :preferredPortList="preferredPortList" />
      <type-select-modal :visible.sync="typeVisible" @callback="distributeConfirmCallback" />
      <number-change-modal :visible.sync="numberVisible" :obj="numberRow" @callback="numberChangeCallback" />
      <edit-form ref="form" :orderSubclassData="orderSubclassData" :preferredPortList="preferredPortList" @callback="handleOk" />
    </a-card>
  </div>
</template>
<script>
  import { STable } from '@/components'
  import { 
    FoamingRuKuOrderPage, 
    FoamingRuKuOrderDelete, 
    FoamingRuKuOrderMulDistribute, 
    FoamingRuKuOrderMulWithdraw ,
    FoamingRuKuOrderForceComplete
  } from '@/api/modular/main/FoamingRuKuOrderManage'
  import { WareOrderTypePage } from '@/api/modular/main/WmsOrderTypeManage'
  import { WareWarehouseEntranceNonPage } from '@/api/modular/main/WmsWarehouseEntranceManage'
  import editForm from './editForm.vue'
  import infoBlock from './infoBlock.vue'
  import typeSelectModal from './typeSelectModal.vue'
  import numberChangeModal from './numberChangeModal.vue'
  export default {
    components: {
      STable,
      editForm,
      infoBlock,
      typeSelectModal,
      numberChangeModal
    },
    data () {
      return {
        advanced: false, // 高级搜索 展开/关闭
        queryParam: {},
        columns: [
          {
            title: '单据编号',
            align: 'center',
            // sorter: true,
            dataIndex: 'orderNo',
            scopedSlots: { customRender: 'linkSlot' }
          },
          {
            title: '入库单类型',
            align: 'center',
            // sorter: true,
            dataIndex: 'orderSubclassName'
          },
          {
            title: '入库方式',
            align: 'center',
            // sorter: true,
            dataIndex: 'orderDistributeType',
            scopedSlots: { customRender: 'taskModelscopedSlots' }
          },
          {
            title: '批次',
            align: 'center',
            // sorter: true,
            dataIndex: 'batch'
          },
          {
            title: '密度',
            align: 'center',
            // sorter: true,
            dataIndex: 'materialDensity'
          },
          {
            title: '下料产线',
            align: 'center',
            //sorter: true,
            dataIndex: 'blankingProductionLine',
            scopedSlots: { customRender: 'blankingProductionLineSlots' }
          },
          {
            title: '单据总数量',
            align: 'center',
            //sorter: true,
            dataIndex: 'orderQuantityTotal'
          },
          {
            title: '入库口',
            align: 'center',
            dataIndex: 'preferredPortName'
          },
          {
            title: '创建时间',
            align: 'center',
            dataIndex: 'createdTime'
          },
          {
            title: '创建人',
            align: 'center',
            dataIndex: 'createdUserName'
          },
          {
            title: '状态',
            align: 'center',
            // sorter: true,
            dataIndex: 'orderStatus',
            scopedSlots: { customRender: 'orderStatusscopedSlots' }
          },
          {
            title: '备注',
            align: 'center',
            // sorter: true,
            dataIndex: 'remarks'
          }
        ],
        tstyle: { 'padding-bottom': '0px', 'margin-bottom': '10px' },
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          this.selectedRowKeys = []
          this.selectDels = []
          this.selectDistributes = []
          this.selectWithdraws = []
          this.infoId = null
          let params = {...this.queryParam}
          if ((params.dateRange instanceof Array) && params.dateRange.length===2) {
            params.SearchBeginTime = params.dateRange[0] + ' 00:00:00'
            params.SearchEndTime = params.dateRange[1] + ' 23:59:59'
            delete params.dateRange
          } else {
            delete params.dateRange
            delete params.SearchBeginTime
            delete params.SearchEndTime
          }
          return FoamingRuKuOrderPage(Object.assign(parameter, params)).then((res) => {
            let _arr = res.data.rows || []
            if (_arr.length>0){
              this.onViewDetail(_arr[0])
            }
            return res.data
          })
        },
        orderSubclassData:[],
        orderStatusData: [],
        preferredPortList:[],
        blankingProductionLineList:[],
        selectedRowKeys: [],
        selectDels: [],
        selectDistributes: [],
        selectWithdraws: [],
        infoId:null,
        infoOrderNo:'',
        typeVisible:false,
        confirmDistributes:[],
        numberVisible:false,
        numberRow:{}
      }
    },
    created () {
      const _options = this.$options
      this.orderStatusData = _options.filters['dictData']('order_status')
      this.blankingProductionLineList = _options.filters['dictData']('blanking_production_line')
      if (this.hasPerm('fp_rk_action')) {
        this.columns.push({
          title: '操作',
          width: '120px',
          align: 'center',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        })
      }
    },
    mounted(){
      this.getInitSelectOptions()
    },
    methods: {
      /**
       * 查询参数组装
       */
      getInitSelectOptions(){
        Promise.all([
          WareOrderTypePage(408733612789829),
          WareWarehouseEntranceNonPage('1')
        ]).then(response=>{
          this.orderSubclassData = response[0].data || []
          this.preferredPortList = response[1].data || []
        }).catch(()=>{
          
        })
      },
      switchingDate () {
        const obj = JSON.parse(JSON.stringify(this.queryParam))
        return obj
      },
      FoamingRuKuOrderDelete (record) {
        FoamingRuKuOrderDelete(record).then((res) => {
          if (res.success) {
            this.$message.success('删除成功')
            this.$refs.table.refresh()
          } else {
            this.$message.error('删除失败') // + res.message
          }
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      handleOk () {
        this.$refs.table.refresh()
      },
      onViewDetail(obj){
        if (this.infoId===obj.id) {
          this.infoId = null
          this.infoOrderNo = ''
        } else {
          this.infoId = obj.id;
          this.infoOrderNo = obj.orderNo
        }
      },
      onEdit(obj){
        if (!this.hasPerm('FoamingRuKuOrder:edit')) return false;
        if (obj.orderStatus!==1 && obj.orderStatus!==4) return false
        this.$refs.form.init('edit',obj)
        //abc
      },
      onDel(obj){
        if (obj.orderStatus!==1 && obj.orderStatus!==4) return false
        this.dealDel([obj.id])
      },
      onForceComplete(obj){
        if (obj.orderStatus!==2) return false
        this.$confirm({
          title: '确定要进行强制完成操作吗？',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk:()=>{
            this.handleForceComplete(obj.id,(f)=>{
              if (f) {
                this.$refs.table.refresh()
              }
            })
          }
        });
      },
      onOpenNumberChangeModal(obj){
        if (obj.orderStatus!==2 && obj.orderStatus!==3) return false
        this.numberVisible = true
        this.numberRow = obj
      },
      numberChangeCallback(){
        this.$refs.table.refresh()
      },
      onDistribute(obj){
        if (obj.orderStatus!==1 && obj.orderStatus!==4) return false
        this.dealDistribute([obj.id])
      },
      onWithdraw(obj){
        if (obj.orderStatus!==1 && obj.orderStatus!==2) return false
        this.dealWithdraw([obj.id])
      },
      onMulDel(){
        this.dealDel(this.selectDels)
      },
      onMulDistribute(){
        this.dealDistribute(this.selectDistributes)
      },
      onMulWithdraw(){
        this.dealWithdraw(this.selectWithdraws)
      },
      dealDel(ids){
        if (!this.hasPerm('FoamingRuKuOrder:delete')) return false;
        this.$confirm({
          title: '确定要进行删除操作吗？',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk:()=>{
            this.handleDelete(ids,(f)=>{
              if (f) {
                if (this.infoId && ids.indexOf(this.infoId)>=0) {
                  this.infoId = null
                }
                this.$refs.table.refresh()
              }
            })
          }
        });
      },
      dealDistribute(ids){
        this.confirmDistributes = ids
        this.typeVisible = true
      },
      distributeConfirmCallback(val){
        let params = {id:this.confirmDistributes,orderDistributeType:val}
        this.handleDistribute(params,(f)=>{
          if (f) {
            this.$refs.table.refresh()
          }
        })
      },
      dealWithdraw(ids){
        this.$confirm({
          title: '确定要进行撤回操作吗？',
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk:()=>{
            this.handleWithdraw(ids,(f)=>{
              if (f) {
                this.$refs.table.refresh()
              }
            })
          }
        });
      },
      handleForceComplete(id,callback){
        this.$loading.show()
        FoamingRuKuOrderForceComplete(id).then(()=>{
          this.$loading.hide()
          callback(true)
        }).catch(()=>{
          this.$loading.hide()
          callback(false)
        })
      },
      handleDelete(id,callback){
        this.$loading.show()
        let params = {id}
        FoamingRuKuOrderDelete(params).then(()=>{
          this.$loading.hide()
          callback(true)
        }).catch(()=>{
          this.$loading.hide()
          callback(false)
        })
      },
      handleDistribute(params,callback){
        this.$loading.show()
        FoamingRuKuOrderMulDistribute(params).then(()=>{
          this.$loading.hide()
          callback(true)
        }).catch(()=>{
          this.$loading.hide()
          callback(false)
        })
      },
      handleWithdraw(id,callback){
        this.$loading.show()
        FoamingRuKuOrderMulWithdraw(id).then(()=>{
          this.$loading.hide()
          callback(true)
        }).catch(()=>{
          this.$loading.hide()
          callback(false)
        })
      },
      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        let arr1=[],arr2=[],arr3=[]
        selectedRows.forEach((item)=>{
          if (item.orderStatus===1 || item.orderStatus===4) {
            arr2.push(item.id)
            arr1.push(item.id)
          }
          if (item.orderStatus===1 || item.orderStatus===2) {
            arr3.push(item.id)
          }
        })
        this.selectDels = arr1
        this.selectDistributes = arr2
        this.selectWithdraws = arr3
      }
    }
  }
</script>
<style lang="less">
  .table-operator {
    margin-bottom: 18px;
  }
  button {
    margin-right: 8px;
  }
</style>